#!/bin/bash

#Generate password if none was set
if [ -z $ZEND_ADMIN_PASSWORD ]; then
	ZEND_ADMIN_PASSWORD=`cat /root/zend-password 2> /dev/null`
if [ -z $ZEND_ADMIN_PASSWORD ]; then
    export ZEND_ADMIN_PASSWORD=`date +%s | sha256sum | base64 | head -c 8`
    echo $ZEND_ADMIN_PASSWORD > /root/zend-password
fi
fi

HOSTNAME=`hostname`
APP_IP=`/sbin/ifconfig eth0| grep 'inet addr:' | awk {'print $2'}| cut -d ':' -f 2`

#Grant permissions on Apache logs
usermod -a -G adm zend

#Debug
#sed -i 's/zend_gui.debugModeEnabled = false/zend_gui.debugModeEnabled = true/' /usr/local/zend/gui/config/zs_ui.ini
#sed -i 's/zend_gui.logVerbosity = NOTICE/zend_gui.logVerbosity = DEBUG/' /usr/local/zend/gui/config/zs_ui.ini
#sed -i 's/zend_server_daemon.log_verbosity_level=2/zend_server_daemon.log_verbosity_level=5/' /usr/local/zend/etc/zsd.ini
#sed -i 's/zend_jobqueue.daemon.log_verbosity_level=2/zend_jobqueue.daemon.log_verbosity_level=5/' /usr/local/zend/etc/jqd.ini
#sed -i 's/zend_monitor.daemon.log_verbosity_level=2/zend_monitor.daemon.log_verbosity_level=5/' /usr/local/zend/etc/monitor_node.ini
#sed -i 's/zend_deployment.daemon.log_verbosity_level=2/zend_deployment.daemon.log_verbosity_level=5/' /usr/local/zend/etc/zdd.ini

/usr/local/zs-init/init.php

echo "Zend Server is ready for use
Your application is available at http://$APP_IP
To access Zend Server, navigate to http://$APP_IP:10081
Your admin password is `/usr/local/zs-init/stateValue.php ZEND_ADMIN_PASSWORD`"

MYSQL_HOSTNAME=`/usr/local/zs-init/stateValue.php ZEND_CLUSTER_DB_HOST`
if [ `echo $MYSQL_HOSTNAME|grep :` ]; then
        MYSQL_PORT=`echo $MYSQL_HOSTNAME|cut -d":" -f2`
        MYSQL_HOSTNAME=`echo $MYSQL_HOSTNAME|cut -d":" -f1`
else
	MYSQL_PORT=3306
fi
MYSQL_USERNAME=`/usr/local/zs-init/stateValue.php ZEND_CLUSTER_DB_USER`
MYSQL_PASSWORD=`/usr/local/zs-init/stateValue.php ZEND_CLUSTER_DB_PASSWORD`
MYSQL_DBNAME=`/usr/local/zs-init/stateValue.php ZEND_CLUSTER_DB_NAME`
NODE_ID=`/usr/local/zs-init/stateValue.php NODE_ID`
WEB_API_KEY_NAME=`/usr/local/zs-init/stateValue.php WEB_API_KEY_NAME`
WEB_API_KEY_HASH=`/usr/local/zs-init/stateValue.php WEB_API_KEY_HASH`

#Define Default application
/usr/local/zend/bin/zs-client.sh applicationDefine --name=default --baseUrl="http://<default-server>:80/" --zskey=$WEB_API_KEY_NAME --zssecret=$WEB_API_KEY_HASH > /dev/null 2>&1

if [[ -n $MYSQL_HOSTNAME && -n $MYSQL_USERNAME && -n $MYSQL_PASSWORD ]]; then
echo "Joining cluster"
exec /usr/local/bin/nothing $MYSQL_HOSTNAME $MYSQL_PORT $MYSQL_USERNAME $MYSQL_PASSWORD $MYSQL_DBNAME $NODE_ID $WEB_API_KEY_NAME $WEB_API_KEY_HASH
fi

exec /usr/local/bin/nothing


